import os
import tempfile

import pytest
from flaskr import create_app
from flaskr.db import get_db, init_db

with open(os.path.join(os.path.dirname(__file__), 'data.sql'), 'rb') as f:
    _data_sql = f.read().decode('utf-8')

@pytest.fixture
def app():
    # 创建并打开一个临时文件，返回文件对象和路径
    db_fd, db_path = tempfile.mkstemp()

    app = create_app({
        'TESTING': True,  # 测试模式
        'DATABASE': db_path
    })

    with app.app_context():
        init_db()
        get_db().executescript(_data_sql)
    
    yield app

    os.close(db_fd)
    os.unlink(db_path)

@pytest.fixture
def client(app):
    return app.test_client()  # 测试会使用客户端来向应用发送请求，而不用启动服务器

@pytest.fixture
def runner(app):
    return app.test_cli_runner()